package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.AnswerComment;
import cn.wolfcode.luowowo.comment.query.AnswerCommentQuery;
import cn.wolfcode.luowowo.comment.repository.AnswerCommentRepository;
import cn.wolfcode.luowowo.comment.service.IAnswerCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class AnswerCommentServiceImpl implements IAnswerCommentService {

    @Autowired
    private AnswerCommentRepository repository;

    @Autowired
    private MongoTemplate template;

    public AnswerComment save(AnswerComment comment) {
        comment.setCreateTime(new Date());

       //如果是评论的评论
        if (comment.getType() == AnswerComment.ANSWER_COMMENT_TYPE){
            String refId = comment.getRefComment().getId();
            if (StringUtils.hasLength(refId)){
                AnswerComment refComment = repository.findById(refId).get();
                if (refComment !=null){
                    comment.setRefComment(refComment);
                }
            }
        }
        repository.save(comment);
        return comment;
    }

    public Page query(AnswerCommentQuery qo) {
        Query query = new Query();
        if (qo.getAnswerId() != "") {
            query.addCriteria(Criteria.where("answerId").is(qo.getAnswerId()));
        }

        PageRequest pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.DESC, "createTime");
        //total
        long total = template.count(query, AnswerComment.class);


        query.with(pageable);
        //list
        List<AnswerComment> list = template.find(query, AnswerComment.class);


        return new PageImpl(list, pageable, total);
    }

    public List<AnswerComment> findByAnswerId(String id) {
        return repository.findByAnswerId(id);
    }
}
